﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Xejen.Communication.Http
{
    /// <summary>
    /// 表示Http请求结果
    /// <para>
    /// 使用<see langword="byte[]"/>类型作为返回的数据结果类型，是为了适用所有数据类型，这样可以做到最通用的效果
    /// </para>
    /// </summary>
    /// <creator>marc</creator>
    public class HttpResponse : HttpResponse<byte[]>
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public HttpResponse()
        {

        }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public HttpResponse(Encoding encoding = default) : base(encoding)
        {

        }

        /// <summary>
        /// 返回一个表示成功的<see cref="HttpResponse{T}"/>对象
        /// </summary>
        /// <param name="returnData"></param>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public static new HttpResponse Success(byte[] returnData, Encoding encoding = default)
        {
            HttpResponse response = new HttpResponse(encoding);
            response.ReturnData = returnData;
            response.Code = SuccessCode;

            return response;
        }

        /// <summary>
        /// 返回一个表示失败的<see cref="HttpResponse{T}"/>对象
        /// </summary>
        /// <param name="code"><inheritdoc cref="IResult.Code" path="/summary"/></param>
        /// <param name="exception"><inheritdoc cref="IResult.Exception" path="/summary"/></param>
        public static new HttpResponse Fail(int code, Exception exception = default)
        {
            return new HttpResponse()
            {
                Code = code,
                Exception = exception,
            };
        }

        /// <summary>
        /// 将返回值转为string
        /// </summary>
        /// <returns></returns>
        public string DataToString()
        {
            if (this.ReturnData == null)
            {
                return null;
            }

            return Encoding.GetString(this.ReturnData);
        }

        /// <inheritdoc/>
        public override object GetSerializableObject()
        {
            if (this.IsSuccess)
            {
                return new 
                {
                    Code = this.Code,
                    IsSuccess = this.IsSuccess,
                    ReturnData = DataToString()
                };
            }
            else
            {
                return new
                {
                    Code = this.Code,
                    IsSuccess = this.IsSuccess,
                    ErrorMessage = this.Exception?.Message,
                    StackTrace = this.Exception?.StackTrace
                };
            }
        }
    }
}
